package com.cavy.platform.server;

import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.io.IOException;
import java.util.List;

/**
 * 代理返回值到resultInfo中
 */
public class ResultInfoWarpProcess extends RequestResponseBodyMethodProcessor {
    public ResultInfoWarpProcess(List<HttpMessageConverter<?>> converters, ContentNegotiationManager manager) {
        super(converters, manager);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest
    ) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
        boolean assignableFrom = ResultInfo.class.isAssignableFrom(returnValue.getClass());
        if (assignableFrom) {
            super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
        } else {
            ResultInfo resultInfo = new ResultInfo(returnValue);
            super.handleReturnValue(resultInfo, returnType, mavContainer, webRequest);
        }
    }

}
